package com.jyniubi.gamll.auth.controller;

import com.jyniubi.gamll.auth.service.AuthService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.nio.charset.StandardCharsets;

@Controller
@Slf4j
public class AuthController {
    @Autowired
    private AuthService authService;

    @GetMapping("toLogin.html")
    public String toLogin(@RequestHeader(value = "returnUrl",defaultValue = "http://gmall.com") String returnUrl, Model model){
        try {
            // 解码 returnUrl
            returnUrl = URLDecoder.decode(returnUrl, StandardCharsets.UTF_8.name());
        } catch (UnsupportedEncodingException e) {
            log.error("URL解码失败", e);
        }
        model.addAttribute("returnUrl",returnUrl);
        return "login";
    }

    @PostMapping("login")
    public String login(@RequestParam("loginName") String loginName,
                        @RequestParam("password") String password,
                        @RequestParam("returnUrl")String returnUrl,
                        HttpServletRequest request,
                        HttpServletResponse response
                        ) {
        this.authService.accredit(loginName,password,request,response);
        // 对url进行截取?returnUrl=等号后面的路径
        // http://sso.gmall.com/toLogin.html?returnUrl=http://cart.gmall.com/addCart.html?skuId=26&count=1
        int startIndex = returnUrl.indexOf("returnUrl=") +  "returnUrl=".length();
        returnUrl = returnUrl.substring(startIndex);
        if (StringUtils.isBlank(returnUrl)){
            returnUrl = "http://gmall.com";
        }
        return "redirect:" + returnUrl;
    }
}
